package com.ekko.weatherapp.View;

import android.content.Context;
import android.os.Debug;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.ekko.weatherapp.Model.WeatherModel;
import com.ekko.weatherapp.R;
import com.ekko.weatherapp.tools.Constants;
import com.ekko.weatherapp.tools.HttpUtil;
import com.ekko.weatherapp.tools.ItemBean;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

public class MainActivity extends AppCompatActivity {
    // model，数据层
    private WeatherModel wModel;
    // 请求路径
    final String host = Constants.host;
    // 搜索按钮
    Button searchBtn;
    // 城市输入框
    EditText cityInput;
    // 信息列表
    ListView infoList;
    // 城市名称
    String cityName;
    //创建简单适配器
    SimpleAdapter simpleAdapter;
    //定义List泛型集合,里面存放的是Map键值对, listDate作为ListView的数据源
    List<Map<String, Object>> listDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    // 构造器
    private void init() {
        // 获取model的单例
        wModel = WeatherModel.getInstance();
        initLayout();
    }

    /**
     * 初始化布局控件
     */
    void initLayout() {
        // 找到输入框
        cityInput = findViewById(R.id.cityName);
        // 找到按钮
        searchBtn = findViewById(R.id.searchBtn);
        // 找到列表
        infoList = findViewById(R.id.infoList);
        // 监听事件
        searchBtn.setOnClickListener(listener);
    }

    // 创建监听对象
    Button.OnClickListener listener = new Button.OnClickListener(){
        public void onClick(View v){
            // 获取输入的城市名称
            cityName = cityInput.getText().toString();
            // 判断城市名称不为空
            if (!(cityName.isEmpty() && cityName.equals(""))) {
                // 发送请求
                sendRequest(cityName);
            } else
                Toast.makeText(MainActivity.this, "请输入城市名称", Toast.LENGTH_SHORT).show();
            // 隐藏键盘
            setKeyboardShow();
        }
    };

    void setKeyboardShow() {
        InputMethodManager imm =  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
    }

    /**
     * 发送请求
     * 使用GET方法发送请求,需要把参数加在URL后面，用?连接，参数之间用&分隔
     * 注意字符串连接时不能带空格
     * HttpGet与HttpPost区别在于Get将参数在地址中传递，Post用加密参数传递
     * 使用android-async-http进行http请求
     * @param city 城市名称
     */
    void sendRequest(final String city) {
        // 用于存储参数
        RequestParams params = new RequestParams();
        // 存入参数
        params.put("location", city);
        params.put("key", Constants.appcode);
        // 调用get函数进行请求
        HttpUtil.get(host, params, new JsonHttpResponseHandler() {
            // 重写onSuccess方法 此方法当请求成功时调用
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                // 判断请求返回码 200即为请求返回正确
                if (statusCode == 200) {
                    // 解析返回的json
                    try {
                        // 根据api返回示意进行解析
                        JSONObject obj = response.getJSONArray("HeWeather6").getJSONObject(0);
                        String status = obj.get("status").toString();
                        // 判断返回的状态是否为正确
                        if (status.equals(Constants.statusType.OK)) {
                            String location = obj.getJSONArray("basic").getString(0);
                            // 获取天气数据
                            JSONArray arr = obj.getJSONArray("daily_forecast");
                            // 遍历数组
                            for (int i = 0; i < arr.length(); i ++) {
                                // 数据
                                HashMap<String, String> info = new HashMap<>();
                                // 将每一条需要的信息存到model的数组里
                                info.put(Constants.weatherType.location, location);
                                info.put(Constants.weatherType.minTmp, arr.getJSONObject(i).getString(Constants.weatherType.minTmp));
                                info.put(Constants.weatherType.maxTmp, arr.getJSONObject(i).getString(Constants.weatherType.maxTmp));
                                info.put(Constants.weatherType.dayCons, arr.getJSONObject(i).getString(Constants.weatherType.dayCons));
                                info.put(Constants.weatherType.nightCons, arr.getJSONObject(i).getString(Constants.weatherType.nightCons));
                                info.put(Constants.weatherType.date, arr.getJSONObject(i).getString(Constants.weatherType.date));
                            }
                            // 界面显示
                            setViewShow();
                        } else if (status.equals(Constants.statusType.FAILED)) {
                            // 如果有误
                            Toast.makeText(MainActivity.this, "城市查询失败！", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    // 如果返回码不为200 显示
                    Toast.makeText(MainActivity.this, "请求失败！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 显示界面
     */
    void setViewShow(){
        Log.i("---------------", "开始布局");
//        List<Map<String, Object>> data = getTodayListData();
//        simpleAdapter = new SimpleAdapter(MainActivity.this,
//                listDate,
//                R.layout.layout,
//                new String[]{"dates", "dayCons", "nightCons", "maxTmps", "minTmps"},
//                new int[]{R.id.date, R.id.dayCons, R.id.nightCons, R.id.maxTmp, R.id.minTmp});
        TextView location = findViewById(R.id.localName);
        location.setText(getData("location").get(0).toString());
        TextView nowCons = findViewById(R.id.nowCons);
        nowCons.setText(getData("dayCons").get(0).toString());
        TextView nowTmp = findViewById(R.id.nowTmp);
        nowTmp.setText(getData("maxTmp").get(0).toString());
        simpleAdapter = new SimpleAdapter(MainActivity.this,
                getListData(),
                R.layout.itoday,
                new String[]{"dates", "dayCons", "maxTmps", "minTmps"},
                new int[]{R.id.date, R.id.dayCons, R.id.maxTmp, R.id.minTmp});
        infoList.setAdapter(simpleAdapter);
    }

    /**
     * 获取数据源
     * @return
     */
    List<Map<String,Object>> getListData(){
        ArrayList dayCons = getData(Constants.weatherType.dayCons);
        ArrayList nightCons = getData(Constants.weatherType.nightCons);
        ArrayList maxTmps = getData(Constants.weatherType.maxTmp);
        ArrayList minTmps = getData(Constants.weatherType.minTmp);
        ArrayList dates = getData(Constants.weatherType.date);
//        // version 1.0
//        listDate = new ArrayList<>();
//
//        for (int j = 0; j < getData().size(); j++) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("dates", dates.get(j).toString());
//            map.put("dayCons", "白天：" + dayCons.get(j).toString());
//            map.put("nightCons", "晚上：" + nightCons.get(j).toString());
//            map.put("maxTmps", "最高温：" + maxTmps.get(j).toString() + "℃");
//            map.put("minTmps", "最低温：" + minTmps.get(j).toString() + "℃");
//            listDate.add(map);
//        }
        listDate = new ArrayList<>();

        for (int j = 1; j < getData().size(); j++) {
            Map<String, Object> map = new HashMap<>();
            map.put("location", getData("location"));
            map.put("dates", dates.get(j).toString());
            map.put("dayCons", dayCons.get(j).toString());
            map.put("nightCons", nightCons.get(j).toString());
            map.put("maxTmps", maxTmps.get(j).toString());
            map.put("minTmps", minTmps.get(j).toString());
            listDate.add(map);
        }
        return listDate;
    }

    /**
     * 获取所有信息
     * @return 信息
     */
    List getData(){
        ArrayList list = wModel.getWeatherInfo();
        return list;
    }

    /**
     * 获取部分信息
     * @param infoName 信息名称
     * @return 信息
     */
    ArrayList getData(String infoName) {
        ArrayList list = wModel.getWeatherInfo(infoName);
        return list;
    }

    /**
     * 清除listview
     */
    void clearView(){
        // 获取当前listview的adapter
        ArrayAdapter adapter = (ArrayAdapter) infoList.getAdapter();
        // listview多少个组件
        int count = adapter.getCount();
        // 如果有数据
        if (count > 0) {
            // 先清空所有数据
            infoList.setAdapter(new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1));
        }
    }
}
